package com.hmall.item.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.domain.dto.PageDTO;
import com.hmall.common.domain.query.PageQuery;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.MqHelper;
import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.service.IItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
public class ItemController {

    private final IItemService itemService;
    private final MqHelper mqHelper;

    @ApiOperation("分页查询商品")
    @GetMapping("/page")
    public PageDTO<ItemDTO> queryItemByPage(PageQuery query) {
        // 1.分页查询
        Page<Item> result = this.itemService.page(query.toMpPage("update_time", false));
        // 2.封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }

    @ApiOperation("根据id批量查询商品")
    @GetMapping
    public List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids) {
        return this.itemService.queryItemByIds(ids);
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id) {
        return BeanUtils.copyBean(this.itemService.getById(id), ItemDTO.class);
    }

    @ApiOperation("新增商品")
    @PostMapping
    public void saveItem(@RequestBody ItemDTO itemDTO) {
        // 新增
        Item item = BeanUtils.copyBean(itemDTO, Item.class);
        boolean b = this.itemService.save(item);
        if (!b) {
            log.error("新增商品失败");
            return;
        }
        // 获取保存后的id
        Long itemId = item.getId();
        // 将id设置到DTO中
        itemDTO.setId(itemId);
        // 发送消息
        this.mqHelper.sendMessage("item.topic", "item.save", itemDTO);
    }

    @ApiOperation("更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        boolean b = this.itemService.updateById(item);
        if (!b) {
            log.error("更新商品失败");
        }
        this.mqHelper.sendMessage("item.topic", "item.update", List.of(item.getId()));
    }

    @ApiOperation("更新商品")
    @PutMapping
    public void updateItem(@RequestBody ItemDTO item) {
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        item.setStatus(null);
        // 更新
        boolean b = this.itemService.updateById(BeanUtils.copyBean(item, Item.class));
        if (!b) {
            log.error("更新商品失败");
        }
        this.mqHelper.sendMessage("item.topic", "item.update", List.of(item.getId()));
    }

    @ApiOperation("根据id删除商品")
    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        boolean b = this.itemService.removeById(id);
        if (!b) {
            log.error("新增商品失败");
            return;
        }
        this.mqHelper.sendMessage("item.topic", "item.delete", id);
    }

    @ApiOperation("批量更新库存")
    @PutMapping("/stock/update")
    public void updateStock(@RequestBody List<OrderDetailDTO> items) {
        try {
            this.itemService.updateStock(items);
        } catch (Exception e) {
            log.error("批量更新商品");
        }
        List<Long> itemIds = items.stream().map(OrderDetailDTO::getItemId).collect(Collectors.toList());
        this.mqHelper.sendMessage("item.topic", "item.update", itemIds);
    }

}
